if(typeof stock_address_ws==='undefined')
{
    stock_address_ws = [];
}
if(typeof address_ws==='undefined')
{
    address_ws = '';
}
'use strict';
var app = angular
        .module('vegaLora',['ngMaterial','ngMessages'])
        .constant('ws',{address: address_ws,stock:stock_address_ws!==undefined&&stock_address_ws.length>0?stock_address_ws:[address_ws]});
app.directive('ngEnter',function(){
    return function(scope,element,attrs){
      element.bind('keydown keypress',function(event){
          if(event.which==13){
              scope.$apply(function(){
                  scope.$eval(attrs.ngEnter,{'event':event});
              });
              event.preventDefault();
          }
      });  
    };
});
app.controller('AppController',function($scope,ws,$interval,$timeout,$mdDialog){  
     $scope.demo_user = typeof demo_user=='boolean'&&demo_user?demo_user:false;
     $scope.select_server = typeof select_server=='boolean'&&select_server?select_server:false;
     $scope.search_ws_address = function(){
         if(get_cookie('ws')!=undefined)
         {
             this.address = get_cookie('ws');
         }
         else
         {
             this.address = ws.address;
         }
         if(ws.address==this.address)
         {
             this.full_settings = false;
         }
         else
         {
             this.full_settings = true;
         }
     };
     $scope.toggleSettings = function()
     {
         if(this.full_settings)
         {
            this.full_settings =false;
         }
         else
         {
            this.full_settings=true;
         }
     };
     $scope.universalAlert = function (message,title)
    {
        if(!title) title = 'Внимание!';
        $mdDialog.show(
            $mdDialog.alert()
              .clickOutsideToClose(true)
              .title(title)
              .textContent(message)
              .ariaLabel(title)
              .ok('Хорошо')
        );
    }
     $scope.parse_vega=function(json)
     {
         try{
            json=JSON.parse(json);
            $scope.last_time = new Date().getTime();
            if(json.cmd=='auth_resp')
            {
                if(json.status)
                {
                    this.user.token = json.token;
                    this.user.command_list = json.command_list;
                    $scope.auth_control();
                }
                else
                {
                    if(json.err_string!=undefined)
                    {
                        // alert(json.err_string);
                        this.universalAlert(json.err_string,'Ошибка!')
                    }
                    else
                    {
                        this.universalAlert('Ошибка авторизации!');
                    }
                }
            }
            else
            {
               console.log('Парсер не знает что делать с тем что пришло'); 
            }
         }
         catch(err)
         {
             console.log('Server прислал чушь');
         }
     };
     $scope.reload_time=0;
     $scope.websocket={
        reload:function()
        {
            $scope.reload_time=2;
            if($scope.websocket.connect!=undefined) 
            {
                $scope.websocket.connect.close();
            }
            try{
                this.connect =new WebSocket($scope.address);
                this.connect.onopen=function(event){
                    console.log('Onopen');
                    $scope.reload_time=0;
                    this.status=true;
                };
                this.connect.onclose=function(event){
                    console.log('Onclose');
                    this.status=false;
                    $scope.reload_time=2;
                };
                this.connect.onerror=function(err){
                    console.log('Onerror');
                     this.status=false;
                     $scope.reload_time=2;
                };
                this.connect.onmessage=function(event){
                    console.log('Onmessage');
                    $scope.parse_vega(event.data);
                };
            }
            catch (err)
            {
                this.status=false;
                $scope.reload_time=2;
            }
        }
    };
     $scope.enter_input = function(){
       var valid = new valid_data();
       if(valid.valid(this.login)&&valid.valid(this.password))
       {
           $scope.auth();
       }
       else
       {
           
       }
     };
     $scope.demo=function()
     {
        $scope.login='demo';
        $scope.password='demo';
        $scope.auth();
     };
    $scope.ping=function()
    {   
        if(this.websocket!=undefined&&this.websocket.connect.status)
        {
            this.websocket.connect.send(JSON.stringify({
               cmd:'ping_req'
            }));
        }
    };
     $scope.auth=function()
     {
         var valid = new valid_data();
         if(valid.valid(this.login)&&valid.valid(this.password))
         {
             if(this.websocket!=undefined&&this.websocket.connect.status)
             {
                 if(this.send_block==0)
                 {
                    $scope.user.login=$scope.login;
                    $scope.user.password=$scope.password;
                   this.websocket.connect.send(JSON.stringify({
                       login:$scope.login,
                       password:$scope.password,
                       cmd:'auth_req'
                   }));
                   this.send_block=2;
                }
                else
                {
                    this.universalAlert('Error time','Ошибка!');
                }
             }
             else
             {
                this.universalAlert('Error connection','Ошибка!');
             }
         }
         else
         {
            this.universalAlert('Error input ','Ошибка!');
         }
     };
     $scope.cheat_arr=ws.stock;
      $scope.index_cheat=0;
     $scope.cheat=function()
     {
         this.index_cheat++;
         if(this.index_cheat>=this.cheat_arr.length)
         {
             this.index_cheat=0;
         }
         this.address=this.cheat_arr[this.index_cheat];
         $scope.websocket.reload();
     };
     $scope.auth_control = function()
     {
        if(this.user.login!=undefined&&this.user.token)
        {
           var my_command_list = new command_list();
           my_command_list.set_command_list_array(this.user.command_list);
           if(my_command_list.get_device_appdata)
           {
                set_cookie('login',this.user.login);
                set_cookie('token',this.user.token);
                set_cookie('command_list',JSON.stringify(this.user.command_list));
                set_cookie('ws_address',JSON.stringify(this.address));
                window.location='./index.html';
           }
           else
           {
            this.universalAlert('Not enough access rights!','Ошибка!');
           }
        }
        else
        {
            console.log('info 199');
        }
     };
     $scope.init = function()
     {
        $scope.send_block =0;
        $scope.user=new Object();
        $scope.ws = ws;
        $scope.search_ws_address();
        $scope.websocket.reload();
        $interval(function(){
        if($scope.send_block!=0)
        {
            $scope.send_block--;
        }
        },1000);
         $interval(function(){
            $scope.reload_time--;
                if(!$scope.websocket.connect.status)
                {
                    if($scope.reload_time!=0)
                    {
                        $scope.websocket.reload();
                    } 
                }
                else
                {
                    $scope.ping();
                    var currentTime = new Date().getTime();
                    var passedTime = $scope.last_time?(currentTime-$scope.last_time):0;
                    if(passedTime>30000)
                    {
                        $scope.websocket.connect.status = false;
                        $scope.reload_time=2;
                        console.log('connect.status = false');
                    }
                }
        },5000);
     };
    $scope.init();
    });
       

